__author__ = 'mars'
import socket
import sys
import struct
import  time

myfile = sys.argv[1]
car_number ='D-12345'
car_number2='E-22345'
car_number3='F-32345'

car_list=[]

# car_list.append(car_number)
# car_list.append(car_number2)
# car_list.append(car_number3)
#
# car_list.append(car_number)
# car_list.append(car_number2)
# car_list.append(car_number3)
#192

HOST = '61.152.242.101'    # The remote host
list1=[]
#HOST = '127.0.0.1'    # The remote host
PORT = 8449             # The same port as used by the server

# for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
#     af, socktype, proto, canonname, sa = res
#     try:
#         s = socket.socket(af, socktype, proto)
#     except socket.error, msg:
#         s = None
#         continue
#     try:
#         s.connect(sa)
#     except socket.error, msg:
#         s.close()
#         s = None
#         continue
#     break
# if s is None:
#     print 'could not open socket'
#     sys.exit(1)
f1=open("f:/yq8.txt",'r').read() # Open a update template file
f2=f1.split(" ")

for fdd in f2:
    list1.append(fdd.decode("hex"))   #Generate to a hex string human readable

def sent_update(need_car):
    s = None
    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error, msg:
            s = None
            continue
        try:
            s.connect(sa)
        except socket.error, msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
        sys.exit(1)


    dt1=""
    n=22
    for a1 in need_car:                #to change the car_number
        list1[n]=a1
        n = n +1

    for dt in list1:
        dt1 +=dt
    print dt1
    print '\n'
    s.sendall(dt1)
    data = s.recv(1024)# 4recv
    print 'Received', repr(data) #print
    s.close()
count1=1
# for car_derail in car_list:
#     print count1
#     if count1 % 15 == 0:
#         time.sleep(15)
#         print "in sleep loop"
#     sent_update(car_derail)
#     time.sleep(2)
#     count1 +=1

f5 = open ('f:/110581.txt','r')
for dd1 in f5:
    print dd1
    car_list.append(dd1.replace('\n',''))

print car_list

for car_derail in car_list:
    print count1
    if count1 % 15 == 0:
        time.sleep(60)
        print "in sleep loop"
    sent_update(car_derail)
    time.sleep(2)
    count1 +=1



